#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: WorkFlowDeal.py
@Author: lijk34925 
@Date: 2025/5/29 13:27
@desc: 请补充本模块功能说明
"""
import time

from qturboframe.lib.webdriver import SeleniumError

from BladeFerm.Lib.Common import logger
from qturboframe.lib.utils.by import By

from BladeFerm.hui2_app import FE


class WorkFlowDeal(object):
    flow_dict = {"risk_001": "批量客户风险等级审批流程",
                 "risk_002": "手工发起等级风险重评",
                 "rule_001": "可疑交易流程"}

    def __init__(self):
        self.flow_id = "risk_001"
        self.flow_name = "批量客户风险等级审批流程"
        self.flow_type = "RISK"     # RISK: 风险子项流程, RULE: 可疑规则流程
        self.tab_name = "任务信息"
        self.flow_page = dict()
        self._driver = FE.driver
        self.wf_page_body = None
        self.tab_headers = None
        self.tab_index = 0
        self.tab_panel = None
        self.wf_task_tab = None
        self.__fund_wf_page()

    def __fund_wf_page(self):
        # Find the workflow page body element
        wf_xpath = f'//div[@class="app-main"]//div[@class="templateBody"]'
        wf_elements = self._driver.find_elements_by_xpath(wf_xpath)
        self.wf_page_body = wf_elements[0] if wf_elements else None
        # If the workflow page body element is found, find the tab headers and tab panels
        if self.wf_page_body:
            tabs_xpath = './/div[@class="h-tabs-nav-wrap"]//div[@class="h-tabs-tab"]'
            self.tab_headers = self.wf_page_body.find_elements_by_xpath(tabs_xpath)
            tab_panel_xpath = './/div[@class="h-tabs-content-wrap"]//div[@class="h-tabs-panel"]'
            tab_panels = self.wf_page_body.find_elements_by_xpath(tab_panel_xpath)
            # If tab panels are found, find the first displayed tab panel
            if tab_panels:
                for ele in tab_panels:
                    if ele.is_displayed():
                        self.tab_panel = ele
                        break
        # Log the completion of the workflow page information search
        logger.info(f"流程页面信息查找完成")

    def get_flow_page(self):
        """
        获取流程页面信息：流程的基本信息，流程信息，审批信息，操作对象等。返回各个区域的web对象
        :return:
        """
        if self.tab_panel:
            self.wf_task_tab = self.tab_panel.find_element_by_xpath('./div[@class="wf-task-tab"]')
            # 获取基本信息
            flow_basic = self.wf_task_tab.find_elements_by_xpath('./div[@class="amlrc-form-content"]/div[@class="process-info"]')
            self.flow_page['流程信息'] = flow_basic[0] if flow_basic else None
            # 获取流程信息
            flow_infos = self.wf_task_tab.find_elements_by_xpath('./div[@class="amlrc-form-content"]/div')
            if flow_infos:
                for flow_info in flow_infos:
                    flow_title_ele = flow_info.find_element_by_xpath('.//*[contains(@class,"form-title")]')
                    flow_title = flow_title_ele.text.strip()
                    self.flow_page[flow_title] = flow_info
            # 获取任务底部操作对象区域
            foot_xpath = './div[@class="foot-opt" and not(contains(@style,"display: none;"))]/div[@class="h-btn-group"]'
            flow_bottom = self.wf_task_tab.find_elements_by_xpath(foot_xpath)
            self.flow_page['操作'] = flow_bottom[0] if flow_bottom else None
        return self.flow_page

    def filter_user_and_remark(self, user_filter: dict, remark_info: dict):
        """
        根据用户筛选条件，过滤用户，并批注. 用户风险等级用户的流程审批的批注操作
        :param user_filter: {唯一客户号：xxx}
        :param remark_info: {批注方式：批量批注|批注全部， 批注内容： xxxx, 批注级别：低风险|中风险|高风险}
        :return:
        """
        user_element = self.flow_page.get("客户信息")
        if user_filter:
            form_element = FE.form(idname={By.XPATH: './/form'}, driver=user_element)
            form_element.auto_fill_group(user_filter)
            form_element.button_option("查询")
            time.sleep(1)
            logger.info(f"筛选客户信息完成")
        if remark_info:
            remark_method = remark_info.get("批注方式", "批注全部")
            remark_text = remark_info.get("批注内容", "")
            remark_level = remark_info.get("批注级别", "中风险")
            # 打开右侧的弹框,选择批注等级和输入批注信息，然后保存
            FE.Button(remark_method, driver=user_element).click()
            time.sleep(0.2)
            drawer = FE.Drawer()
            radio_ele = FE.list(idname={By.XPATH: './/div[@class="h-radio-group"]'}, driver=drawer.drawer)
            radio_ele.click(remark_level)
            FE.textarea(idname={'xpath': './/div[@class="h-input-wrapper"]/textarea'},
                        driver=drawer.drawer).set_value(remark_text)
            FE.button("保存", father=drawer.drawer).click()
            drawer.close()
            logger.info(f"用户风险等级用户的流程审批的批注操作完成")

    def fill_review_info(self, review_info: dict, module_name=None):
        """
        填写审批信息
        :param review_info: {审批意见：xxx, 审批人：xxx}
        :param module_name: 模块名称，默认为"评级结论"，其他如："可疑报送信息"
        :return:
        """
        if not module_name:
            module_name = "评级结论" if review_info.get("是否上报", None) is None else "可疑报送信息"
        review_element = self.flow_page.get(module_name)
        form_review = FE.form(idname={By.XPATH: './/form'}, driver=review_element)
        form_review.auto_fill_group(review_info)
        logger.info(f"填写审批信息完成")

    def click_option(self, operator: str, return_node: str = "初审岗"):
        """
        点击操作按钮
        :param operator: 操作按钮名称
        :param return_node: 退回节点名称
        :return:
        """
        foot_element = self.flow_page.get("操作")
        if foot_element:
            FE.button(operator, driver=foot_element).click()
            logger.info(f"点击操作按钮{operator}完成")
            # 步骤3：点击确定按钮
            if operator in ["初评", "复评", "提交审定", "审定"]:
                FE.msg_box("是否提交流程").click('确定')
                FE.msg_box("成功").click('确定')
            elif operator == "保存":
                FE.msg_box("成功").click('确定')
            elif operator == "退回":
                # 退回流程：先选择退回节点，再点击确认
                table_top_xpath = '//div[@class="h-modal-header"]/div[contains(text(),"退回设置")]/../..'
                layer_element = FE.list(idname={'xpath': table_top_xpath}, father=FE.driver)
                FE.button(idname={'xpath': f'//td/div/span[contains(text(),"{return_node}")]'},
                          father=layer_element.element).click()
                time.sleep(0.3)
                FE.button(text='提交', father=layer_element.element).click()
                time.sleep(0.3)
                FE.msg_box("是否退回流程").click('确定')
                time.sleep(0.1)
                FE.msg_box("是否退回").click('确定')
                time.sleep(0.1)
                FE.msg_box("成功").click('确定')
            else:
                raise SeleniumError(f'操作类型{operator}不正确!')
        else:
            logger.info(f"操作按钮{operator}不存在")

    def rule_user_option(self, module, option, user_filter: dict = None, remark_info: dict = None):
        """
        根据用户筛选条件，过滤用户，并批注. 可疑交易流程的客户信息，流水信息的批注操作
        :param module: 模块名称: 可疑客户信息，可疑交易信息-交易流水，可疑交易信息-账户流水
        :param option: 操作按钮名称： 审核全部，审核报送，审核不报送 // 添加、查看账户及交易，待添加
        :param user_filter: {唯一客户号：xxx}
        :param remark_info: {是否报送：是|否，备注：xxx}
        """
        modules = module.split('-')
        module_element = self.flow_page.get(modules[0])
        if len(modules) == 2:
            # 交易流水和账户流水，先进行条件查询和筛选
            tab_element = FE.home_tab(modules[1], driver=module_element)
            tab_element.switch_tab(modules[1])
            form_flow_ele = FE.form(idname={'xpath': './/form'}, driver=module_element)
            form_flow_ele.auto_fill_group(user_filter)
            form_flow_ele.button_option("查询")
            time.sleep(1)
            logger.info(f"筛选客户信息完成")
        if option in ["添加"]:
            # 添加客户、交易、账户信息
            FE.button(option, driver=module_element).click()
            msg_box = FE.list(idname={'xpath': '//div[@class="h-modal-content"]'})
            form_msg_ele = FE.form(idname={'xpath': './/form'}, driver=msg_box.element)
            form_msg_ele.auto_fill_group(remark_info)
            form_msg_ele.button_option("查询")
            time.sleep(1)
            table_ele = FE.table_new(driver=msg_box.element)
            table_ele.click_row_by_ids(1, 1)
            msg_box.click("确定")
            logger.info(f"可以交易流程的{module}信息添加完成")
        if option in ["审核报送", "审核不报送"]:
            # 勾选第一行第一列
            table_ele = FE.table_new(driver=module_element)
            table_ele.click_row_by_ids(1, 1)
        # 点击目标操作按钮，添加备注，提交
        if option in ["审核全部", "审核报送", "审核不报送"]:
            FE.button(option, driver=module_element).click()
            msg_box = FE.msg_box("备注")
            form_msg_ele = FE.form(idname={'xpath': './/form'}, driver=msg_box.element)
            form_msg_ele.auto_fill_group(remark_info)
            msg_box.click("确定")
            logger.info(f"可以交易流程的{module}信息添加批注完成")